//
//  HMComposeViewController.swift
//  MyWeibo
//
//  Created by apple on 16/4/26.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        setupUI()
    }
    //在界面显示完成后设置第一响应者为textView
    override func viewDidAppear(animated: Bool) {
        
        //调用父类
        super.viewDidAppear(animated)
        //设置为第一响应者
//        textView.becomeFirstResponder()
    }
    
    
    /// 切换键盘
    private func switchKeyboard(){
        
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        // 控制器通知 toolBar 当前显示的是什么键盘
        composeToolBar.isSystemKeyboard = textView.inputView == nil
        // 重新加载输入的视图
        textView.reloadInputViews()
        if !textView.isFirstResponder() {
            textView.becomeFirstResponder()
        }
    }

    //创建选择图片的方法
    func selectPicture(){
        
        //创建一个pivkviewcontroller
        let vc = UIImagePickerController()
        
        //设置代理 实现代理方法
        vc.delegate = self
        
        //弹出照片控制器
        presentViewController(vc, animated: true, completion: nil)
        
        
    }
    
    /// 发送微博
    @objc private func send(){
        if pictureView.hidden {
            update()
        }else{
            upload()
        }
    }
    
    /// 发送图片微博
    private func upload(){
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        // 请求参数
        let params = [
            "access_token": HMUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!,
        ]
        let data = UIImagePNGRepresentation(self.pictureView.images.first!)!
        HMNetworkTools.sharedTools.upload(urlString, parameters: params, datas: ["pic": data]) { (responseObject, error) -> () in
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    /// 发送文字微博
    private func update(){
        // 发送文字微博
        // 请求地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        // 请求参数
        let params = [
            "access_token": HMUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "status": textView.text!
        ]
        
        // 发送请求
        HMNetworkTools.sharedTools.request(HMRequestMethod.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil {
                print("发送失败\(error)")
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }


    
    //键盘的监听方法
    @objc private func keyboardChageFrame(noti:NSNotification){
        
        //获取到键盘的结束位置
        let endFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //        print(noti.userInfo)
        //更改底边栏的约束
        composeToolBar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(endFrame.origin.y - SCREENH)
        }
        
        //添加动画效果改变
        UIView.animateWithDuration(0.25) { () -> Void in
            //刷新当前控件和子控件的布局
            self.view.layoutIfNeeded()
        }
        
        //        self.view.layoutIfNeeded()
    }
    
    
    func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        //设置导航栏内容
        setupNav()
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        
        
        
        
        //设置控件约束
        composeToolBar.snp_makeConstraints { (make) -> Void in
            
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(44)
            
        }
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(100)
            make.leading.equalTo(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(pictureView.snp_width)
            
        }
        
        //添加一个键盘的监听者
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
       
        
    }
    
    
//    override func viewDidLayoutSubviews() {
//        super.viewDidLayoutSubviews()
//        for value in textView.subviews{
//            print(value)
//            print(value.frame)
//        }
//    }
//    
    //设置导航栏内容
    func setupNav(){
        
        //设item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "back")
        
        navigationItem.titleView = titleView
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //        let atr:NSMutableAttributedString
        //atr.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(20),NSStrokeWidthAttributeName:1,NSStrokeColorAttributeName:UIColor.blueColor()], range: range)
    }
    //返回方法的实现
    @objc private func back(){
        
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //懒加载控件
    
    private lazy var composeToolBar:HMComposeToolBar = {
        
        //创建一个toolbar
        let toolBar = HMComposeToolBar(frame: CGRectZero)
        
        //设置子控件要执行的闭包
        toolBar.buttonClickClosure = {[weak self](type:HMComposeToolBarButtonType) in
            
//            print("点击了\(type)按钮")
            
            //选择点击响应按钮实现的方法
            switch type {
                //    case Picture = 0,Mention,Trend,Emoticon,Add
                
            case.Picture:
                self?.selectPicture()
            case.Mention:
                break
            case.Trend:
                break
            case.Emoticon:
                self?.switchKeyboard()
            case.Add:
                break
                
            }
            
        }
        
        return toolBar
    }()
    
    //懒加载表情
    private lazy var emoticonKeyboard: HMEmoticonKeyboard = {
        let keyboard = HMEmoticonKeyboard()
        keyboard.frame.size = CGSize(width: SCREENW, height: 216)
        return keyboard
    }()

    //懒加载发送按钮
    private lazy var rightButton : UIButton = {
        //创建一个按钮
        let rightbutton = UIButton(textColor: UIColor.whiteColor(), fontSize: 14)
        //设置文字
        rightbutton.setTitle("发送", forState: UIControlState.Normal)
        //设置不同状态下的背景图
        rightbutton.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        rightbutton.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        rightbutton.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        //设置不同状态的文字颜色
        rightbutton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        
        //设置大小
        rightbutton.frame.size = CGSize(width: 45, height: 28)
        
        
        return rightbutton
        
    }()
    
    
    //懒加载横条
    private lazy var titleView:UILabel = {
        //创建一个label
        let titleView = UILabel()
        //指定行数
        titleView.numberOfLines = 0
        //指定文字颜色
        titleView.textColor = UIColor.blackColor()
        //设定文字居中
        titleView.textAlignment = .Center
        //设置文字大小
        titleView.font = UIFont.systemFontOfSize(15)
        //取到账户名字
        if let name = HMUserAccountViewModel.sharedViewModel.account?.name {
            //拼接title
            let text = "快闪开，我要开始装逼了\n\(name)"
            //求出name所在的字符串的范围
            let range = (text as NSString).rangeOfString(name)
            let attrText = NSMutableAttributedString(string: text)
            
            //按照字符串的范围设置文字的各种属性
            attrText.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(14),NSLigatureAttributeName:1,NSStrokeColorAttributeName:UIColor.blueColor()], range: range)
            //设置父文本
            titleView.attributedText = attrText
            
        }else{
            //代表没有读取到用户信息
            titleView.text = "发微博"
        }
        
        
        //设置自适应大小
        titleView.sizeToFit()
        
        return titleView
    }()
    
    //懒加载textView
    private lazy var textView:HMTextView = {
        
        //创建一个textView
        let textView = HMTextView()
        //设置代理
        textView.delegate = self
        
        //设置占位文字
        textView.placeholder = "喂 妖妖灵嘛  这里有人装逼 场面控制不住了~~"
        //设置字体
        textView.font = UIFont.systemFontOfSize(14)
        //拖动的时候消失键盘（系统提示警告）
        textView.keyboardDismissMode = .OnDrag
        //开启垂直方向弹簧效果
        textView.alwaysBounceVertical = true
        
        return textView
    }()
    
    
    /// 懒加载pictureView
    private lazy var pictureView:HMComposePictureView = {
        
        let v = HMComposePictureView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
        
        //调用闭包执行选择图片的方法
        v.selectedPictureClosure = { [weak self] in
            
            self?.selectPicture()
        }
 
        return v
    }()
    
}
//添加相片的代理
extension HMComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    

    //添加图片方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
     
        //取到图片 缩放
        let image = image.scaleToWidth(600)
        //转换二进制
//        let data = UIImagePNGRepresentation(image)
        
        //把选择的图片添加到数组中
        pictureView.addImage(image)
        //销毁照片控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}


extension HMComposeViewController:UITextViewDelegate{
    
    //代理方法监听textview的值得改变
    func textViewDidChange(textView:UITextView){
        //当有值得时候开启发送用户交互
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}
